package com.rc.activity;

import java.util.Random;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.nostra13.universalimageloader.cache.disc.naming.HashCodeFileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.SimpleBitmapDisplayer;
import com.rc.custom.MyImageView;
import com.rc.net.uploadfile;
import com.rc.util.Const;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class ImageViewScreen extends BaseActivity implements OnClickListener {

	private MyImageView imgView;
	private RelativeLayout rlTakePic;
	private LinearLayout llRetake, llUpload, llCancel, llProgress;
	private boolean isShowFooter = true;
	private Bitmap photo;
	private Uri imageUri;
	private DisplayImageOptions options;
	private ImageLoader imageLoader;
	private String mString;

	public static void callIntentBitMap(Context ct, String url) {
		Intent it = new Intent(ct, ImageViewScreen.class);
		it.putExtra("IMAGE_SDCARD", url);
		ct.startActivity(it);
	}

	public static void callIntentViewSDCard(Context ct, String url) {
		Intent it = new Intent(ct, ImageViewScreen.class);
		it.putExtra("imageUrl", url);
		it.putExtra("isShowFooter", false);
		ct.startActivity(it);
	}

	@Override
	protected void onCreate(Bundle arg0) {
		// TODO Auto-generated method stub
		super.onCreate(arg0);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		if (getIntent().hasExtra("isShowFooter")) {
			isShowFooter = getIntent().getBooleanExtra("isShowFooter", true);
			if (!isShowFooter) {
				getWindow().setFlags(
						WindowManager.LayoutParams.FLAG_FULLSCREEN,
						WindowManager.LayoutParams.FLAG_FULLSCREEN);
			}
		}
		// config image loader
		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
				this).threadPriority(Thread.NORM_PRIORITY - 2)
				.denyCacheImageMultipleSizesInMemory()
				.discCacheFileNameGenerator(new HashCodeFileNameGenerator())
				.discCacheSize(50 * 1024 * 1024)
				// 50 Mb
				.tasksProcessingOrder(QueueProcessingType.LIFO)
				.writeDebugLogs() // Remove for release app
				.build();
		// Initialize ImageLoader with configuration.
		ImageLoader.getInstance().init(config);
		imageLoader = ImageLoader.getInstance();

		setContentView(R.layout.main_image_view);

		options = new DisplayImageOptions.Builder()
				.showImageForEmptyUri(R.drawable.abs__ab_bottom_solid_dark_holo) // resource
																					// or
																					// drawable
				.showImageOnFail(R.drawable.abs__ab_bottom_solid_dark_holo) // resource
																			// or
																			// drawable
				.resetViewBeforeLoading(false) // default
				.delayBeforeLoading(1000).cacheInMemory(false) // default
				.bitmapConfig(Bitmap.Config.ARGB_8888) // default
				.displayer(new SimpleBitmapDisplayer()) // default
				.build();

		llRetake = (LinearLayout) findViewById(R.id.llRetake);
		llUpload = (LinearLayout) findViewById(R.id.llUpload);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		imgView = (MyImageView) findViewById(R.id.imgView);
		rlTakePic = (RelativeLayout) findViewById(R.id.rlTakePic);
		llProgress = (LinearLayout) findViewById(R.id.llProgress);

		llCancel.setOnClickListener(this);
		llRetake.setOnClickListener(this);
		llUpload.setOnClickListener(this);
		if (getIntent().hasExtra("IMAGE_SDCARD")) {

			mString = getIntent().getStringExtra("IMAGE_SDCARD");
			Log.e("String URI", mString);
			imageUri = Uri.parse(mString);
			imageLoader.displayImage(mString, imgView, options);

		}

		if (getIntent().hasExtra("imageUrl")) {
			photo = Util.DisplayImageSDCard(Const.FILE_KEY
					+ getIntent().getStringExtra("imageUrl"),
					ImageViewScreen.this);

		}

		if (isShowFooter) {
			((LinearLayout) findViewById(R.id.llFooter))
					.setVisibility(View.VISIBLE);
		} else {
			((LinearLayout) findViewById(R.id.llFooter))
					.setVisibility(View.GONE);
		}
		if (imageUri != null) {
			photo = BitmapFactory.decodeFile(uploadfile
					.getFilePathFromContentUri(imageUri,
							ImageViewScreen.this.getContentResolver()));
		}

	}

	@Override
	protected void onResume() {
		super.onResume();
		if (photo != null) {
			// imageLoader.displayImage(mString,imgView);
			// imgView.setImageBitmap(photo);
		}
	}

	public void ViewImage(Bitmap photo) {
		if (photo != null) {
			imgView.setImageBitmap(photo);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.llRetake:
			Intent cameraIntent = new Intent(
					android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
			startActivityForResult(cameraIntent, Const.CAMERA_REQUEST);
			break;
		case R.id.llCancel:
			finish();
			break;
		case R.id.llSave:
			finish();
			break;
		case R.id.llUpload:

			if (Util.isNetworkActivated(ImageViewScreen.this)) {
				rlTakePic.setVisibility(View.GONE);
				llProgress.setVisibility(View.VISIBLE);
				new uploadImage().execute("");
				Thread thread = new Thread() {
					@Override
					public void run() {
						try {
							while (true) {
								sleep(2000);

								finish();
							}
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				};

				thread.start();

			} else {
				String mfile = Const.FILE_KEY + Util.getTodaysDate() + "_"
						+ Util.getCurrentTime() + "_" + new Random().nextInt()
						+ ".png";
				Util.SaveImage(photo, mfile);
			}
			break;

		default:
			break;
		}
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == Const.CAMERA_REQUEST
				&& resultCode == Activity.RESULT_OK) {
			Bitmap photo = (Bitmap) data.getExtras().get("data");
			this.photo = photo;
			imgView.setImageBitmap(photo);
		}
	}

	private class uploadImage extends AsyncTask<String, Void, String> {

		protected String doInBackground(String... urls) {
			// if (photo == null) {
			// return null;
			// }
			// uploadfile upload = new uploadfile(ImageViewScreen.this, photo);

			uploadfile upload = new uploadfile(ImageViewScreen.this, photo);
			String success = upload.uploadFileWithUri(imageUri);
			return success;
		}

		protected void onPostExecute(String result) {
			if (result == null) {
				showToast(getString(R.string.upload_failed));
			}
			if (result.indexOf("success") >= 0) {
				showToast(getString(R.string.upload_success));
			} else {
				showToast(getString(R.string.upload_failed));
			}
		}
	}

}
